<template>
  <div v-loading="loading">
    <el-tree
      @check="permission_change"
      :default-checked-keys="permissions"
      node-key="id"
      :props="tree_props"
      :data="permission_tree"
      :default-expanded-keys="permissions"
      show-checkbox
    >
    </el-tree>
    <div class="text-center" v-if="pdata.isEdit">
      <el-button @click="allot" :loading="btnload">更新</el-button>
    </div>
  </div>
</template>

<script>
import { permissionTree, getRole,rolePermission } from "@/api";

export default {
  data() {
    return {
      loading:false,
      btnload:false,
      tree_props: {
        label: "display_name",
        children: "children"
      },
      permissions: [],
      permission_tree:[]
    };
  },
  props:['pdata'],
  created() {
    this.loading = true
    permissionTree(
      res => {
        this.permission_tree = res.data.tree;
        this.fetchInfo()
      },
      err => {
        this.loading - false
      }
    );
  },
  methods: {
    fetchInfo() {
      getRole(
        this.pdata.id,
        res => {
          this.loading = false;
          let data = res.data;
          if (data) {
            let per = [];
            for (var i in data.permissions) {
              per.push(data.permissions[i].id);
            }
            this.permissions = per
          }
        },
        err => {
          this.loading = false;
        }
      );
    },
    permission_change(data, checked) {
      this.permissions = checked.checkedKeys;
    },
    allot(){
      this.btnload = true
      rolePermission(this.pdata.id,this.permissions,(res)=>{
        this.btnload = false
        this.$emit("close", true);
      },(err)=>{
        this.btnload = false
      })
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
